﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Contione.RabbitMQ.Client
{
    /// <summary>
    /// mq 启动类库
    /// </summary>
    public static class RabbitMQSetup
    {
        /// <summary>
        /// 依赖注入使用RabbitMQ
        /// </summary>
        /// <param name="services"></param>
        public static IServiceCollection AddRabbitMQ(this IServiceCollection services)
        {
            services.AddTransient<IRabbitMQClient, RabbitMQClient>(x =>
            {
                var configuration = x.GetService<IConfiguration>();
                return new RabbitMQClient(configuration);
            });

            return services;
        }

        /// <summary>
        /// 注册消费者
        /// </summary>
        /// <param name="services"></param>
        public static void RegisterRabbitMQInvoker(this IServiceCollection services)
        {
            var configuration = services.BuildServiceProvider().GetService<IConfiguration>();

            var types = AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(a => a.GetTypes().Where(t => t.BaseType != null &&
                                                         (t.BaseType.Name == typeof(WorkQueuesBase<>).Name
                                                          || t.BaseType.Name == typeof(PublishSubscribeBase<>).Name
                                                          || t.BaseType.Name == typeof(RpcServerBase<,>).Name)
                ));
            if (types != null && types.Any())
            {
                foreach (var type in types)
                {
                    services.AddSingleton(type);
                    var queue = services.BuildServiceProvider().GetService(type) as QueueBase;
                    if (queue != null) queue!.Execute();
                }
            }
        }
    }
}